package com.naiterui.ehp.bs.weixin.service;

import cn.hutool.json.JSONUtil;
import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.bo.patient.PatientBO;
import com.naiterui.ehp.bs.weixin.constant.WeixinConstant;
import com.naiterui.ehp.bs.weixin.feign.PatientFeignClient;
import com.naiterui.ehp.bs.weixin.repository.mysql.WeixinInfoRepository;
import com.naiterui.ehp.bs.weixin.security.api.JwtService;
import com.naiterui.ehp.bs.weixin.security.bean.JwtUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Slf4j
@Service
@AllArgsConstructor
public class JwtServiceImpl implements JwtService {

    private final WeixinInfoRepository weixinInfoRepository;
    private final PatientFeignClient patientFeignClient;

    @Override
    public JwtUser loadUser(Long userId) {
        String cacheStr = RedisUtil.valueOps().getString(WeixinConstant.USER_JWT_CACHE + userId.toString());
        PatientBO patientInfo = Optional.ofNullable(cacheStr).map(str -> JSONUtil.toBean(str, PatientBO.class)).orElse(null);
        if (patientInfo == null) {
            patientInfo = patientFeignClient.getPatientInfo(null, null, userId);
            if (patientInfo == null) {
                throw new UsernameNotFoundException("userId=" + userId);
            }
            RedisUtil.valueOps().setString(WeixinConstant.USER_JWT_CACHE + userId.toString(), JSONUtil.toJsonStr(patientInfo), 60 * 5);
        }
        return new JwtUser(JwtUser.USER_TYPE_PATIENT, patientInfo.getPatientId(), new Date());
    }
}
